package com.hundsun.cprs.yyt.web.action.goods;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.service.classify.domain.Classify;
import com.hundsun.cprs.yyt.service.classify.enums.ClassifyIsDeletedYOrNEnum;
import com.hundsun.cprs.yyt.service.classify.service.ClassifyService;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.dto.UserLoginInfo;
import com.hundsun.cprs.yyt.service.common.dto.UserLoginResult;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsWithArea;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsQuery;
import com.hundsun.cprs.yyt.service.goods.dto.AttributeForm;
import com.hundsun.cprs.yyt.service.goods.dto.AttributeInfo;
import com.hundsun.cprs.yyt.service.goods.dto.AttributeItem;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.enums.EnumGoodsStatus;
import com.hundsun.cprs.yyt.service.goods.service.AttributeService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsWithAreaService;
import com.hundsun.cprs.yyt.util.ValidateUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.vo.JsonModel;

@Controller
@RequestMapping("goods/")
public class GoodsAction extends BaseAction {

    @Autowired
    private AttributeService attributeService;
    @Autowired
    private ClassifyService classifyService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private GoodsWithAreaService goodsWithAreaService;
    @Autowired
    private GoodsSkuService goodsSkuService;

    @RequestMapping("list")
    public void queryList(@ModelAttribute("query")GoodsQuery query){
        goodsService.queryGoodsByPage(query);
    }
    
    @RequestMapping("getGoods")
    public void getGoods(@ModelAttribute("query")GoodsQuery query,String callBack,ModelMap model){
        if (query.getAreaCode() != null) {
            goodsService.queryAreaGoodsList(query);
        } else {
            goodsService.queryGoodsByPage(query);
        }
        model.put("callBack", callBack);
    }
    
    @RequestMapping("skus")
    @ResponseBody
    public JsonModel getGoodsSkus(String areaCode,Integer goodsId){
        List<GoodsSpecs> skus = goodsSkuService.selectGoodsSpecsList(goodsId, areaCode);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        for(GoodsSpecs sku : skus){
            Map<String,Object> item = new HashMap<String,Object>();
            item.put("skuId", sku.getId());
            item.put("goodsStock", sku.getGoodsStock());
            item.put("availableStock", sku.getAvailableStock());
            item.put("skuItem", StringUtils.join(((JSONObject)JSON.parse(sku.getGoodsSpecs())).values()," "));
            result.add(item);
        }
        return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"成功",result);
    }

    @RequestMapping(value = "add",method = RequestMethod.GET)
    public void add(@ModelAttribute("data")GoodsInfo goodsInfo, ModelMap model){
        model.addAttribute("ParentclassifyList", classifyService.selectOneClassify(ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode()));
    }

    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    public JsonModel add(@RequestBody GoodsInfo goodsInfo){
        try {
            if (ValidateUtil.validate(goodsInfo.getGoodsDetail())){
                return new JsonModel(JsonModel.RESULD_CODE_FAIL,"富文本非法字符输入");
            }
            goodsService.createGoods(goodsInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品新增成功");
        } catch (Exception e) {
            log.error("商品新增异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }

    @RequestMapping(value = "edit.htm",method = RequestMethod.GET)
    public void edit(@RequestParam("goodsId")Integer goodsId, ModelMap model){
        GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(goodsId);
        model.addAttribute("data",goodsInfo);
        // 查询所有一级分类
        model.addAttribute("ParentclassifyList", classifyService.selectOneClassify(ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode()));
        // 查询一级分类下的所有二级分类
        model.addAttribute("childClassifyList", classifyService.selectTwoClassifyByParentId(goodsInfo.getClassify().getParentId(), ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode()));
    }

    @RequestMapping(value = "edit",method = RequestMethod.POST)
    @ResponseBody
    public JsonModel edit(@RequestBody GoodsInfo goodsInfo){
        try {
            if (ValidateUtil.validate(goodsInfo.getGoodsDetail())){
                return new JsonModel(JsonModel.RESULD_CODE_FAIL,"富文本非法字符输入");
            }
            goodsService.updateGoods(goodsInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品修改成功");
        } catch (Exception e) {
            log.error("商品修改异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }

    @RequestMapping("view.htm")
    public void view(@RequestParam(value = "goodsId", required = true) Integer goodsId,
                     @RequestParam(value = "areaCode",required = false)String areaCode ,ModelMap model){
        if (areaCode == null || areaCode == ""){
            GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(goodsId);
            model.addAttribute("data",goodsInfo);
        }else{
            GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(goodsId,areaCode);
            model.addAttribute("data",goodsInfo);
            if (areaCode.equals(EnumAreaCode.WHOLESALE_AREA.getCode())){
                //批发区规格
                model.addAttribute("atributeNameInfo", buildAttributeInfos(goodsInfo));

            }else {
                //零售区规格
                List<GoodsSpecs> goodsSpecsList = goodsSkuService.selectGoodsSpecsList(goodsId,areaCode);
                model.addAttribute("goodsSpecsList",goodsSpecsList);
            }
        }
        model.addAttribute("areaCode",areaCode);
    }

    @RequestMapping("delete.json")
    @ResponseBody
    public JsonModel delete(@RequestParam(value = "goodsId", required = true) Integer goodsId){
        try {
            goodsService.deleteGoods(goodsId);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品删除成功");
        } catch (Exception e) {
            log.error("商品删除异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }
    /*
     * 根据父分类id异步查询所有的子分类
     *
     * */
    @RequestMapping("ajax/getClassify")
    @ResponseBody
    public JsonModel getClassify(@RequestParam(value = "classifyId") String classifyId){
        List<Classify> classifyList = classifyService.selectTwoClassifyByParentId(Integer.parseInt(classifyId), ClassifyIsDeletedYOrNEnum.N_CLASSIFY_TYPE.getCode());
        if (classifyList != null) {
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"成功",classifyList);
        }
        return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"成功");
    }

    /*
     * 根据子分类id异步查询所有的属性
     *
     * */
    @RequestMapping("ajax/getAttribute.htm")
    public void getAttribute(@RequestParam("goodsId")Integer goodsId,HttpServletResponse response){
        JSONObject json = new JSONObject();
        List<AttributeItem> attributeInfoList = attributeService.selectAttributeInfo();
        if (attributeInfoList != null) {
            json.put("attributeInfoList", attributeInfoList);
        }
        if (goodsId!=null){
            GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(goodsId,EnumAreaCode.WHOLESALE_AREA.getCode());
            json.put("atributeNameInfo", buildAttributeInfos(goodsInfo));
        }

        try {
            response.getWriter().print(json);
        } catch (Exception e) {
            log.error(e, e);
        }
    }
    
    private List<AttributeInfo> buildAttributeInfos(GoodsInfo goodsInfo) {
        if (goodsInfo.getSkus() != null && !goodsInfo.getSkus().isEmpty()) {
            List<AttributeInfo> attributeInfoList = new ArrayList<>();
            for (GoodsSpecs goodsSpecs : goodsInfo.getSkus()) {
                AttributeInfo attributeInfo = new AttributeInfo();
                List<AttributeForm> attributeFormList = new ArrayList<>();
                if (goodsSpecs.getGoodsSpecs() != null) {
                    Map<String, String> attributeFormMap = JSON.parseObject(goodsSpecs.getGoodsSpecs(), Map.class);
                    for (Map.Entry<String, String> entry : attributeFormMap.entrySet()) {
                        AttributeForm attributeForm = new AttributeForm();
                        attributeForm.setAttributeName(entry.getKey());
                        attributeForm.setAttributeValue(entry.getValue());
                        attributeFormList.add(attributeForm);
                    }
                }
                attributeInfo.setAttributeFormList(attributeFormList);
                attributeInfo.setItemPrice(goodsSpecs.getGoodsPrice());
                attributeInfo.setStockNum(goodsSpecs.getGoodsStock());
                attributeInfo.setQuotaAmount(goodsSpecs.getQuotaAmount());
                attributeInfo.setSkuId(goodsSpecs.getId());
                attributeInfo.setAllocatedStock(goodsSpecs.getAllocatedStock());
                attributeInfoList.add(attributeInfo);
            }
            return attributeInfoList;
        }
        return null;
    }

    @RequestMapping("getUser.htm")
    public String getUserNewWidow(ModelMap model,String id){
        model.addAttribute("id", id);
        return "goods/getUser";
    }

    /*
     * 根据用户名或者手机号异步查询所有的用户列表
     *
     * */
    @RequestMapping("ajax/getUerList.htm")
    public void getUerList(ModelMap model,@RequestParam(value = "account", required = false) String account,@RequestParam(value = "phone", required = false) String phone,@RequestParam(value = "id", required = false) String id,HttpServletResponse response){
        JSONObject json = new JSONObject();
        UserLoginInfo request = new UserLoginInfo();
        if (account != null && account !="") {
            request.setUserAccount(account);
        }
        if(phone != null && phone !=""){
            request.setCellPhone(phone);
        }
        UserLoginResult result=remoteUserService.getUserListByAccount(request);
        List<UserAccountDTO> userAccountDTOs = result.getUserAccountDTOs();
        if (userAccountDTOs != null) {
            json.put("userAccountDTOs", userAccountDTOs);
        }
        try {
            response.getWriter().print(json);
        } catch (Exception e) {
            log.error(e, e);
        }
    }

    @RequestMapping("ajax/validateGoodsCode.json")
    @ResponseBody
    public String validateGoodsCode(@RequestParam("goodsCode") String goodsCode) throws IOException {
        List<GoodsInfo> goodsList=goodsService.selectGoodsByGoodsCode(goodsCode);
        if(goodsList.isEmpty()){
            return "true";
        }else{
            return "false";
        }
    }

    @RequestMapping("cancel/publish.json")
    @ResponseBody
    public JsonModel cancelPublish(@RequestParam("goodsId")Integer goodsId,@RequestParam("areaCode")String areaCode){
        try {
            GoodsWithArea goodsWithArea = new GoodsWithArea();
            goodsWithArea.setGoodsId(goodsId);
            goodsWithArea.setAreaCode(areaCode);
            goodsWithArea.setGoodsStatus(EnumGoodsStatus.CANCEL_PUBLISH.getCode());
            goodsWithAreaService.update(goodsWithArea);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品下架成功");
        } catch (Exception e) {
            log.error("商品下架异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }

    @RequestMapping("rePublish.json")
    @ResponseBody
    public JsonModel rePublish(@RequestParam("goodsId")Integer goodsId,@RequestParam("areaCode")String areaCode){
        try {
            GoodsWithArea goodsWithArea = new GoodsWithArea();
            goodsWithArea.setGoodsId(goodsId);
            goodsWithArea.setAreaCode(areaCode);
            goodsWithArea.setPublishTime(new Date());
            goodsWithArea.setGoodsStatus(EnumGoodsStatus.PUBLISHED.getCode());
            goodsWithAreaService.update(goodsWithArea);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品重新上架成功");
        } catch (Exception e) {
            log.error("商品重新上架异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }
}
